package com.defangit.production.orm;

import com.defangit.production.bll.StockBll;
import com.defangit.production.domain.Stock;
import laogen.hibernate.CommonFinder;
import laogen.hibernate.CommonService;
import laogen.lang.exception.ParameterNotValidException;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;


public class StockService extends CommonService<Stock> implements StockBll{
    @Override
    public Stock addStock(Stock stock) {
        add(stock);
        return get(stock.getId()).orElseThrow(()->ParameterNotValidException.zeroIdOrEntityNonExist("库存信息异常"));
    }

    @Override
    public Stock updateStock(Stock stock) {
        return null;
    }

    @Override
    public StockFinder findAll() {
        return new StockFinderImp(detachedAll());
    }

    public class StockFinderImp extends CommonFinder<Stock> implements StockFinder{
        private DetachedCriteria stockCriteria;

        private StockFinderImp(DetachedCriteria stockCriteria){
            this.stockCriteria = stockCriteria;
        }

        @Override
        public Criteria getCriteria() {
            return this.stockCriteria.getExecutableCriteria(getSession()).addOrder(Order.desc("id"));
        }

        @Override
        public DetachedCriteria getDetachedCriteria() {
            return this.stockCriteria;
        }

        @Override
        public StockFinder manufactureId(Integer manufactureId) {
            if (manufactureId==null) return this;
            this.stockCriteria.add(Restrictions.eq("manufacture.id",manufactureId));
            return this;
        }

        @Override
        public StockFinder storeId(Integer storeId) {
            if (storeId==null) return this;
            this.stockCriteria.add(Restrictions.eq("store.id",storeId));
            return this;
        }
    }
}
